package jinyilw.swing.visuals;

import jinyilw.swing.ColorTools;
import jinyilw.swing.DragCompUtils;
import jinyilw.swing.rlaf.theme.RRootPaneSet;

import javax.swing.JRootPane;
import javax.swing.JWindow;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Window;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;

public class FlatWindow extends JWindow // 图像窗
{
	private static final long serialVersionUID = 716505333572120038L;
	private static RRootPaneSet rootPaneSet;
	protected Image customImage;
	private int opacity = 0;
	protected boolean rounded = true;

	public FlatWindow()
	{
		initGUI();
	}

	public FlatWindow(Window owner)
	{
		super(owner);
		initGUI();
	}

	private void initGUI()
	{
		if (rootPaneSet == null)
			rootPaneSet = RRootPaneSet.getRootPaneSet();
		DragCompUtils.setMovable(getRootPane(), this);
	}

	public void setCustomBGImage(Image img)
	{
		customImage = img;
		if (img != null)
			repaint();
	}

	public void setCustomBGImage(Image img, int x, int y, int w, int h)
	{
		setCustomBGImage(((BufferedImage) img).getSubimage(x, y, w, h));
	}

	public Image getCustomImage()
	{
		return customImage;
	}

	public void setOpacity(int opacity)
	{
		this.opacity = opacity;
	}

	public boolean isRounded()
	{
		return rounded;
	}

	public void setRounded(boolean b)
	{
		rounded = b;
		if (b)
			setShape(new RoundRectangle2D.Double(0, 0, getWidth(), getHeight(),
					5, 5));
		else
			setShape(null);
	}

	public void setResizable(boolean b)
	{
		if (b)
			DragCompUtils.setResizeable2(getContentPane(), this);
	}

	public void setMoveable(boolean b)
	{
		if (b)
			DragCompUtils.setMovable(getContentPane(), this);
	}

	@Override
	public void setBounds(int x, int y, int width, int height)
	{
		super.setBounds(x, y, width, height);
		if (width == 0 || height == 0)
			return;
		if (rounded)
			setShape(new RoundRectangle2D.Double(0, 0, width, height, 5, 5));
	}

	@Override
	protected JRootPane createRootPane()
	{
		JRootPane rp = new FlatRootPane();
		rp.setOpaque(true);
		return rp;
	}

	class FlatRootPane extends JRootPane
	{
		private static final long serialVersionUID = -6354719692392570597L;

		@Override
		public void updateUI()
		{
		}

		@Override
		protected void paintComponent(Graphics g)
		{
			if (customImage != null)
				g.drawImage(customImage, 0, 0, getWidth(), getHeight(), null);
			else
				g.drawImage(rootPaneSet.bgImage, 0, 0, getWidth(), getHeight(),
						null);
			if (opacity > 10 && opacity <= 255)
			{
				g.setColor(
						ColorTools.getAlphaColor(rootPaneSet.bgColor, opacity));
				g.fillRect(0, 0, getWidth(), getHeight());
			}
		}
	}
}
